package jude.java.framework.test;
import jude.java.money.spring.ContextHolder;
import jude.java.util.Utils;
import junit.framework.TestCase;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;


public abstract class SpringTestCase extends TestCase {

	private ApplicationContext context = new ClassPathXmlApplicationContext(
			new String[] { "/applicationContext-main.xml" });
	protected SessionFactory sessionFactory;
	protected Session session;

	protected ApplicationContext getContext() {
		return context;
	}
	
	protected void setUp() {
		sessionFactory = (SessionFactory) context.getBean("sessionFactory");
		session = SessionFactoryUtils.getSession(sessionFactory, true);
		session.setFlushMode(FlushMode.AUTO);	//NEVER
		TransactionSynchronizationManager.bindResource(sessionFactory,
				new SessionHolder(session));
		ContextHolder.setApplicationContext(context);
	}

	protected void tearDown() throws Exception {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
		SessionFactoryUtils.releaseSession(session, sessionFactory);
	}
	
	protected void waiting(Thread thread) {
		if (thread == null)
			return;
		while (thread.isAlive()) {
			Utils.sleep(3000);
		}
	}
}
